package list.medium;

import list.ListNode;

/**
 *
 * 删除链表的倒数第 N 个结点
 *
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 *
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 * 示例 2：
 *
 * 输入：head = [1], n = 1
 * 输出：[]
 * 示例 3：
 *
 * 输入：head = [1,2], n = 1
 * 输出：[1]
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
 */
public class RemoveNthNodeFromEndOfList_19 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || head.next == null) return null;
        ListNode cur = head, past = head;
        for(int i = 0; i < n; i++) {
            past = past.next;
        }
        if (past == null) {
            return head.next;
        }
        while (past.next != null) {
            cur = cur.next;
            past = past.next;
        }

        cur.next = cur.next.next;
        return head;
    }
}
